package LeetCode;

import java.util.*;

public class LC_229 {

    public static List<Integer> majorityElement(int[] nums) {
        Set<Integer> res = new HashSet<>();
        Arrays.sort(nums);
        int sum = 1, n = nums.length;
        if(n<3){
            for (int i:nums
            ) {
                res.add(i);
            }
            return new ArrayList<>(res);
        }
        for(int i=0;i<n-1;i++){
            if(nums[i] == nums[i+1]){
                sum++;
                if(sum>n/3){
                    res.add(nums[i]);
                    sum=1;
                    while(i+1<n&&nums[i]==nums[i+1]){
                        i++;
                    }

                }
            }
            else {
                sum=1;
            }
        }
        return new ArrayList<>(res);
    }

    public static void main(String[] args) {
        int[] nums = new int[]{4,1,3,1,3,3,1,2,3,2,4,2,1,4,4,4,4,4};
        for (int i:majorityElement(nums)
             ) {
            System.out.println(i);
        }
    }
}
